#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
#endregion

namespace KLib.Input
{
    public class GamePad
    {
        #region Fields
        PlayerIndex playerIndex;
        GamePadState state;
        GamePadState prvState;

        TimeSpan rumbleDuration;
        bool isRumblingWithTimer = false;
        #endregion

        #region Properties

        #region States
        public GamePadState State
        {
            get { return state; }
        }

        public GamePadState PreviousState
        {
            get { return prvState; }
        }
        #endregion

        #endregion

        #region Initialization

        public GamePad(PlayerIndex playerIndex)
        {
            this.playerIndex = playerIndex;
        }

        #endregion

        #region Events
        public event EventHandler Press;
        #endregion

        #region Methods

        public void Update(GameTime gameTime)
        {
            prvState = state;
            state = Microsoft.Xna.Framework.Input.GamePad.GetState(playerIndex);
            //Subtract elapsed time from the rumble timer
            if (rumbleDuration.TotalMilliseconds >= 0)
            {
                rumbleDuration -= gameTime.ElapsedGameTime;
            }

            //If the time for rumbling is up, stop it
            if (isRumblingWithTimer && rumbleDuration.TotalMilliseconds <= 0)
            {
                isRumblingWithTimer = false;
                SetRumble(0, 0);
            }

            if (state.Buttons != prvState.Buttons
                && Press != null)
                Press(this, null);
        }

        /// <summary>
        /// Gets if the specified button was pressed this frame
        /// </summary>
        public bool IsButtonPressed(Buttons button)
        {
            return state.IsButtonDown(button) && prvState.IsButtonUp(button);
        }

        /// <summary>
        /// Gets if the specifed button is pressed
        /// </summary>
        public bool IsButtonDown(Buttons button)
        {
            return state.IsButtonDown(button);
        }

        public void SetRumble(float left, float right)
        {
            Microsoft.Xna.Framework.Input.GamePad.SetVibration(playerIndex, left, right);
        }

        public void SetRumble(float seconds, float left, float right)
        {
            isRumblingWithTimer = true;
            rumbleDuration = TimeSpan.FromSeconds(seconds);
            SetRumble(left, right);
        }
        #endregion

        #region Helper Methods

        #endregion
    }
}
